package 队列;

public class MyQueue {
    private Node head = null;
    private Node tail = null;
    private int size = 0;

    public void offer(int v){
        Node node = new Node(v);
        if (tail == null){
            head = node;
        }else {
            tail.next = node;
        }
        tail = node;
        size++;
    }

    public int poll(){
        if (size == 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        if (size == 1){
            head = tail = null;
            size = 0;
            return head.val;
        }else {
            Node deleteNode = head;
            head = head.next;
            size--;
            return deleteNode.val;
        }
    }

    public int peek(){
        if (size == 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        return head.val;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int size(){
        return size;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Node cur = head; cur != null; cur = cur.next){
            stringBuilder.append(cur.val);
            if (cur.next != null){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
